const redeem_overlay = document.getElementById('redeem_overlay');
const redeem_close = document.getElementById('redeem_close');
function showRedeem() {
    redeem_overlay.style.display = 'flex';
}
redeem_close.addEventListener('click', (e) => {
    redeem_overlay.style.display = 'none';
});

function showRedeemNotice(message, type = 'success') {
    const notification = document.getElementById('redeem_message');
    notification.textContent = message;
    notification.style.display = 'block';
    notification.classList.add(type);

    // 5 秒后隐藏通知
    setTimeout(() => {
        notification.classList.remove(type);
        notification.style.display = 'none';
    }, 5000); // 5000 毫秒 = 5 秒
}

function redeemCode() {
    const inputs = document.querySelectorAll('input[class="redeem_input flex-col"]'); // 获取所有输入框
    const values = Array.from(inputs).map(input => input.value); // 提取值
    const redeem_code = values.join('-');
    if (redeem_code.length < 19) {
        showRedeemNotice('请输入有效的兑换码', 'warning');
        return;
    }
    const url = '/credits/redeem_points';
    // 发送 POST 请求
    fetch(url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json', // 设置请求头
        },
        body: JSON.stringify({redeem_code: redeem_code}), // 将数据转换为 JSON 格式
    })
    .then(response => response.json()) // 解析响应为 JSON
    .then(result => {
        showRedeemNotice(result.msg, result.status)
        if (result.status === 'success') {
            inputs.forEach(input => {
                input.value = ''; // 清空输入框
            });
            document.getElementById('user_points').textContent = result.points;
        }
    });
}

(() => {
    // 获取所有输入框
    const redeem_inputs = [...document.querySelectorAll('.redeem_input.flex-col')];

    // 统一的处理函数
    const handleInput = (e, idx) => {
        const el = e.target;
        let val = el.value.toUpperCase().replace(/\s+/g, ''); // 统一大写
        e.target.value = e.target.value.toUpperCase().replace(/\s+/g, '');

        // 1. 粘贴或键入完整兑换码（包含 - ）
        if (val.includes('-')) {
            const parts = val.split('-');
            let targetIdx = idx;

            parts.forEach(part => {
                if (targetIdx >= redeem_inputs.length) return;
                redeem_inputs[targetIdx].value = part.slice(0, redeem_inputs[targetIdx].maxLength);
                targetIdx++;
            });

            // 光标跳到下一个空框或最后一个框
            const nextEmpty = redeem_inputs.findIndex((inp, i) => i >= idx && !inp.value);
            const focusIdx = nextEmpty === -1 ? redeem_inputs.length - 1 : nextEmpty;
            redeem_inputs[focusIdx].focus();
            redeem_inputs[focusIdx].setSelectionRange(
                redeem_inputs[focusIdx].value.length,
                redeem_inputs[focusIdx].value.length
            );

            return;
        }

        // 2. 正常输入达到 maxlength 时自动前进一格
        if (val.length >= el.maxLength && idx < redeem_inputs.length - 1) {
            redeem_inputs[idx + 1].focus();
        }
    };

    // 3. 删除键（Backspace）时，若当前框已空则退回上一格
    const handleKeydown = (e, idx) => {
        if (e.key === 'Backspace' && e.target.value === '' && idx > 0) {
            redeem_inputs[idx - 1].focus();
        }
    };

    // 绑定事件
    redeem_inputs.forEach((input, idx) => {
        input.addEventListener('input', e => handleInput(e, idx));
        input.addEventListener('keydown', e => handleKeydown(e, idx));
    });
})();